import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_read_record.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/post/post_detail_page.dart';
import 'package:osc/ui/pages/project/project_detail_page.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/real_rich_text.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/web_scaffold.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///阅读记录
class ReadRecordList extends StatefulWidget {
  const ReadRecordList({Key key,}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new ReadRecordListState();
  }
}

class ReadRecordListState extends State<ReadRecordList> with AutomaticKeepAliveClientMixin<ReadRecordList> {
  ReadRecordListState();

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  int bannerCount = 3;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscReadRecord> list;

  List<String> catalogs = ["所有", "软件", "话题", "博客", "新闻", "代码", "资讯", "翻译"];//1-软件|2-话题|3-博客|4-新闻|5代码|6资讯|7-翻译

  RefreshController controller = RefreshController(initialRefresh: true);
  ScrollPhysics scrollPhysics = ScrollPhysics();


  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: buildListView(),
    );
  }


  buildListView(){
    return ListView.separated(
      itemBuilder: (BuildContext context, int index) {
        if (size == 0) {
          return NoDataWidget();
        } else {
          return buildListItem(index);
        }
      },
      separatorBuilder: (BuildContext context, int index) {
        return SmallWidgets.buildLine();
      },
      itemCount: isLoadedData && size == 0? 1 : size,
      physics: scrollPhysics,
    );
  }

  buildListItem(int index){
    OscReadRecord item = list.elementAt(index);
    return GestureDetector(
      onTap: (){
        if(item.type == 0){
          jump2PageForResult(WebScaffold(title: item.title, url: item.url,));
        } else if(item.type == 1){
          jump2PageForResult(ProjectDetailPage(id: item.oscId));
        } else {
          jumpToPageForResult(PostDetailPage(id: item.oscId, type: item.type));
        }
      },
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.all(Dimens.gap_activity_horizontal),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            buildTitle(item),
//            buildDescription(item.title),
            buildBottom(item),
          ],
        ),
      ),
    );
  }

  buildTitle(OscReadRecord item){
    List<TextSpan> textSpans = List<TextSpan>();
    TextSpan tsCatalog = TextSpan(
      text: " ${catalogs[item.type]} ",
      style: TextStyle(
        backgroundColor: Colors.black12,
          fontSize: Dimens.font_sp14,
      ),
    );
    textSpans.add(tsCatalog);
    textSpans.add(buildTextSpan(" "+item.title));
    return RealRichText(
      textSpanList:textSpans,
    );
  }

  buildTextSpan(String text){
    return TextSpan(
      text: text,
      style: TextStyle(color: Colors.black, fontSize: Dimens.font_sp14,),
    );
  }

  buildImageSpan(String imageName, EdgeInsets margin){
    return ImageSpan(
      AssetImage(PdUtil.getImagePath(imageName)),
      imageWidth: Dimens.view_item_tag_height_small,
      imageHeight: Dimens.view_item_tag_height_small,
      margin: margin,
    );
  }
  
  buildTitleIcon(bool show, String imageName){
    return Offstage(
      offstage: !show,
      child: Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_tag_height_smaller, fit: BoxFit.fitWidth,),
    );
  }
  
  buildDescription(String msg){
    return Padding(
        padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_smaller),
      child: buildText(msg, Colors.black54, Dimens.font_sp10),
    );
  }


  buildBottom(OscReadRecord item){
    String authorName;
    if(StringUtil.isEmpty(item.authorName)){
      authorName = "暂无作者署名";
    } else {
      authorName = item.authorName;
    }
    return Padding(
      padding: EdgeInsets.only(top: paddingChildVertical),
      child: Row(
        children: <Widget>[
          buildText("@$authorName  ${DateUtil.getDateStrByTimeStr(item.pubDate, format: DateFormat.YEAR_MONTH_DAY)}", Colors.black54, Dimens.font_sp10),
          Expanded(
            child:  buildBottomItem("ic_comment_30", "${item.commentCount}"),
          ),
        ],
      ),
    );
  }

  buildBottomItem(String imageName, String text){
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_icon_height_smallest, fit: BoxFit.fitWidth,),
        buildText(" $text", Colors.black54, Dimens.font_sp10)
      ],
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    await httpRepository.getReadRecords().then((resp){
      isLoadedData = true;
      if(resp != null && resp.success){
        OscBaseListEntity<OscReadRecord> entity = resp;
        if(entity != null){
          list = entity.listResult;
          size = list?.length??0;
        }
      }
    });
    if(mounted) {
      setState(() {
        if(size > 0){
          controller.loadNoData();
        }
        controller.refreshCompleted();
      });
    }
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

  @override
  bool get wantKeepAlive => true;
}
